<template>
  <div class="maingl">
    <div class="main_spac1">
      <div class="main_white padding10">
        <div class="main_crumbs">
          <div class="main_crumbs_l">
            <a href="javascript:;" @click="$router.back(-1)">
              <i class="el-icon-arrow-down"></i>返回
            </a>
            <em>|</em>
            <span>导入辅助资料</span>
          </div>
        </div>

        <div class="main_tree">
          <h3 class="main_tree_h">名称</h3>
          <div class="main_tree_b">
            <el-tree
              :data="list"
              show-checkbox
              node-key="id"
              ref="tree"
              v-loading="listLoading"
              element-loading-text="加载中"
              icon-class="el-icon-arrow-right"
              :default-checked-keys="defaultkeys"
              highlight-current
              default-expand-all
              @check-change="checkChange"
              :props="defaultProps"
              style="min-height: 540px"
              :render-content="renderContent"
            >
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <span>{{ node.label }}</span>
                <span>
                  <el-link
                    type="danger"
                    @click="delet(data.id)"
                    v-if="data.company_id > 0"
                    >删除</el-link
                  >
                </span>
              </span>
            </el-tree>
          </div>
        </div>

        <div class="newConBox_p100 paddingBottom10" id="newConBox">
          <img
            ref="deleteImg"
            v-show="false"
            src="@/assets/images/trash.png"
            alt=""
          />
          <div class="newConBox_h32">
            <div :class="['newConBox ', { on: searchBarFixed }]">
              <el-button type="primary" @click="Grant" v-repeatClick
                >确认导入</el-button
              >
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  datum_list,
  datum_use,
  datum_delete,
} from "@/api/commodity/commoditySupporting";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import { render } from "nprogress";

export default {
  components: {},
  data() {
    return {
      // 列表数据
      list: [],
      listLoading: false,
      // 树型tree
      defaultkeys: [],
      defaultProps: {
        children: "selfNext",
        label: "title",
      },
      // 监听滚动
      searchBarFixed: false,
      imgsrc: this.$refs["deleteImg"],
    };
  },
  mounted() {
    window.addEventListener("scroll", this.handleScroll);
    this.changeTreeClass();
  },
  destroyed() {
    window.removeEventListener("scroll", this.handleScroll);
  },
  methods: {
    // 监听滚动
    handleScroll() {
      let scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      scrollTop + document.documentElement.clientHeight >
      document.getElementById("newConBox").offsetTop + 200
        ? (this.searchBarFixed = false)
        : (this.searchBarFixed = true);
    },
    // 监听勾选
    checkChange(row, rows, rowu) {
      let key = this.$refs.tree
        .getCheckedKeys()
        .concat(this.$refs.tree.getHalfCheckedKeys());
      this.list.map((m) => {
        if (m.selfNext && m.selfNext.length != 0) {
          m.selfNext.map((w) => {
            w.isSelect = false;
          });
        }
      });
      key.forEach((e) => {
        this.list.map((p) => {
          if (p.selfNext && p.selfNext.length != 0) {
            p.selfNext.map((w) => {
              if (e == w.id) {
                w.isSelect = true;
                return;
              }
            });
          }
        });
      });
    },
    // 删除
    delet(id) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, { id: id })) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: id }
      );
      this.$confirm("是否删除标签?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          datum_delete(data).then((res) => {
            if (res.errcode == 0) {
              this.$message({
                message: "删除成功",
                type: "success",
              });
              this.datum_list();
            } else {
              this.$message.error(res.errmsg);
            }
          });
        })
        .catch(() => {});
    },
    // 确认授权
    Grant() {
      let attribute = []; // 不可互调SKU属性  3
      let brand = []; // 商品品牌         4
      let tag = []; // 商品标签         2
      let unit = []; // 计量单位         1
      this.list.map((w) => {
        if (w.selfNext && w.selfNext.length != 0) {
          w.selfNext.map((p) => {
            if (p.isSelect) {
              if (p.type == 1) {
                this.typeNext(unit, p);
              }
              if (p.type == 2) {
                this.typeNext(tag, p);
              }
              if (p.type == 3) {
                this.typeNext(attribute, p);
              }
              if (p.type == 4) {
                this.typeNext(brand, p);
              }
            }
          });
        }
      });
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        {
          attribute: JSON.stringify(attribute),
          brand: JSON.stringify(brand),
          tag: JSON.stringify(tag),
          unit: JSON.stringify(unit),
        }
      );
      datum_use(data).then((res) => {
        if (res.errcode == 0) {
          this.$message({
            message: "导入成功",
            type: "success",
          });
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    typeNext(arry, p) {
      arry.push({
        id: p.id,
        title: p.title,
        type: p.type,
        company_id: p.company_id,
        status: 1,
      });
    },
    // 菜单列表
    datum_list() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name
      );
      datum_list(data).then((res) => {
        this.listLoading = false;
        if (res.errcode == 0) {
          let arry = [];
          res.data.list.map((e) => {
            if (e.selfNext && e.selfNext.length != 0) {
              switch (e.type) {
                case 2:
                  e.title = "商品标签";
                  break;
                case 3:
                  e.title = "不可互调SKU规格";
                  break;
                case 4:
                  e.title = "商品品牌";
                  break;
                case 1:
                  e.title = "计量单位（可互调SKU规格）";
                  break;
              }
              e.selfNext.map((w) => {
                if (w.isSelect) {
                  arry.push(w.id);
                }
              });
            }
          });
          this.defaultkeys = arry;
          this.list = res.data.list;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    renderContent(h, { node, data, store }) {
      let src = this.$refs["deleteImg"].src;
      let classname = "";
      if (node.level === 3) {
        classname = "levelname";
      }
      if (node.level === 2 && node.childNodes.length === 0) {
        classname = "levelname";
      }
      setTimeout(() => {
        this.changeTreeClass();
      }, 30);

      if (data.company_id > 0) {
        return (
          <p class={classname}>
            {node.label}
            <i
              class="el-icon-delete"
              on-click={() => this.delet(data.id)}
              style="padding-left:10px"
            ></i>
          </p>
        );
      } else {
        return <p class={classname}>{node.label}</p>;
      }
    },
    changeTreeClass() {
      var classDomList = document.getElementsByClassName("levelname"); // 改变这几个样式
      for (var i = 0; i < classDomList.length; i++) {
        classDomList[i].parentNode.style.cssText = "float: left";
        classDomList[i].parentNode.className =
          "el-tree-node__content option-wrapper";
        classDomList[i].parentNode.parentNode.parentNode.style.marginLeft =
          "70px";
        classDomList[i].parentNode.parentNode.parentNode.style.cssText =
          "border-bottom:1px solid #ebeef5";
      }
    },
  },
  created() {
    // 菜单列表
    this.datum_list();
  },
};
</script>
<style lang="scss" scoped>
.maingl {
  .main_table {
    margin-top: 20px;
    /deep/.el-table--border th:first-child .cell {
      padding-left: 70px;
    }
    /deep/.el-table--border td:first-child .cell {
      padding-left: 60px;
    }
    .maingl_ch {
      display: inline-block;
      margin-left: 10px;
      /deep/.el-checkbox__label {
        padding-left: 10px;
      }
    }
  }
  .newConBox.on {
    margin-left: -10px;
    padding-left: 10px;
  }
}
// /deep/.main_tree .is-focusable>.el-tree-node__content {
//   border-bottom: 0;
// }
// /deep/.el-tree-node__content {
//   border-bottom: 1px solid #ccc;
// }
.demo {
  display: inline-block !important;
  width: 19px !important;
}
</style>
